package com.yc.boot.log.aop;

import cn.hutool.core.util.ObjectUtil;
import com.yc.boot.common.model.response.Outcome;
import com.yc.boot.log.aspect.WorkLog;
import com.yc.boot.log.business.LoggerBusiness;
import com.yc.boot.sys.business.SysUserBusiness;
import com.yc.boot.sys.model.UserInfo;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author 杨智杰
 * @since 2021/11/10 10:51
 */
@Aspect
@Component
public class LogAspect {
    @Resource
    private SysUserBusiness sysUserBusiness;

    @Resource
    private LoggerBusiness loggerBusiness;

    @Pointcut("@annotation(com.yc.boot.log.aspect.WorkLog)")
    public void exudeService() {
    }

    @SneakyThrows
    @Around("exudeService()")
    public Outcome doAround(ProceedingJoinPoint pjp) {
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        WorkLog workLog = method.getAnnotation(WorkLog.class);
        UserInfo loginUser = sysUserBusiness.getUserInfo();
        if (ObjectUtil.isNull(loginUser)) {
            return Outcome.failure("未检测到当前登录用户!无法加入业务日志!").setCode(500);
        }
        com.yc.boot.log.entity.WorkLog log = new com.yc.boot.log.entity.WorkLog();
        log.setCreateBy(loginUser.getId()).setCreateTime(new Date()).setParam(workLog.value()).setIsDel(false);
        loggerBusiness.setCache(log);
        try {
            return (Outcome) pjp.proceed();
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }
}
